import { Injectable } from "@nestjs/common";
import { CreateMenuDto } from "./dto/create-menu.dto";
import { UpdateMenuDto } from "./dto/update-menu.dto";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { Like, Repository } from "typeorm";
import { Menu } from "@/modules/system/menu/entities/menu.entity";
import { generateMenuTree } from "@/common/utils/common";

@Injectable()
export class MenuService {
    constructor(
        @InjectRepository(Menu)
        private readonly menuRepository: Repository<Menu>
    ) {
    }
    
    async create(createMenuDto: CreateMenuDto) {
        return ResultData.ok(instanceToPlain(await this.menuRepository.save(createMenuDto)));
    }
    
    async findAll(findAllDto) {
        const { parentId, menuName } = findAllDto;
        const where = {
            ...(parentId ? { parentId } : null),
            ...(menuName ? { menuName: Like(`%${menuName}%`) } : null)
        };
        return ResultData.ok(instanceToPlain(await this.menuRepository.find({
            order: {
                sort: "DESC",
                id: "DESC"
            },
            where
        })));
    }
    
    async findAllTree() {
        const res = await this.menuRepository.find({
            order: {
                sort: "DESC",
                id: "DESC"
            }
        });
        
        return ResultData.ok(instanceToPlain(generateMenuTree(res.map(v => ({
            ...v,
            value: v.id,
            label: v.menuName,
        })), -1)));
    }
    
    findOne(id: number) {
        return `This action returns a #${id} menu`;
    }
    
    async update(id: number, updateDto) {
        return ResultData.ok(await this.menuRepository.update(id, updateDto), "更新成功");
    }
    
    async remove(id: number) {
        return ResultData.ok(await this.menuRepository.delete(id), "删除成功");
    }
}
